﻿using System.Collections.Generic;
using UnityEngine;
using LuaInterface;

namespace WentStateMachine
{
    public class StateMachineLuaDriver : IDriver
    {
        private LuaState currentState;

        public StateMachineLuaDriver()
        {
#if !MULTI_STATE
            currentState = LuaState.Get(default);
#else
            throw (new System.NotImplementedException());
#endif
        }

        private List<StateMachineController> controllers = new List<StateMachineController>();

        public IStateMachineController Drive(StateMachineController asset)
        {
            var instance = ScriptableObject.Instantiate<StateMachineController>(asset);
            instance.SetGlobalParam("LuaState", currentState);
            instance.Init();
            controllers.Add(instance);
            return instance;
        }

        public void OnUpdate()
        {
            if (controllers == null)
                return;

            foreach (var control in controllers)
            {
                do
                {
                    control.OnUpdate();
                } while (control.ParamHasChanged);
            }
        }
    }
}